<?php


namespace app\reception\controller;


use app\common\classes\BehaviorRedis;
use app\common\classes\VoucherRedis;
use app\common\model\Bookshelf;
use app\common\model\ChangeLog;
use app\common\model\ExamineNovel;
use app\common\model\QuickLink;
use app\common\model\QuickUser;
use app\reception\classs\AdvertBehavior;
use app\reception\logic\NovelLogic;
use app\reception\logic\UserLogic;
use think\Db;

class Novel extends Common
{
    protected $middleware = [
        'VerifyAuth' => ['except' => ['read']],
    ];

    protected $beforeActionList = [
        'headRead' => ['only' => 'read'],//切换投放号,或记录广告行为
    ];

    protected $link = null;

    /**
     * 变更信息，及广告信息记录
     */
    protected function headRead()
    {
        if (!$this->user) {
            /**
             * 因为前置方法在VerifyAuth中间件之前执行，所以加了这个判断，也就不走中间件了（VerifyAuth中间件作用只是判断读者是否存在）
             */
            json(['code' => 2,'msg' => 'Request to read, but user is null'])->send();
            die;
        }
        $token = input('token');
        if ($token != '') {
            $this->link = QuickLink::getByToken($token);
            if (!$this->link) {
                errJson('token值异常，非法传参')->send();
                die;
            }
            if ($this->link->quick_id != $this->quickAppId) {
                errJson('链接信息和快应用信息比对失败，非法传参')->send();
                die;
            }
            UserLogic::changeUser($this->user, $this->link, $this->isWhite);//用户变更记录
            $redis = new BehaviorRedis();
            $redis->setLinkUv($this->link->id, $this->uid);
        }
        $pageParam = input('pageParam');
        if ($pageParam != '') {
            /**
             * 记录广告行为
             */
            if ($this->link) {
                $AdvertBehavior = new AdvertBehavior();
                $AdvertBehavior->writeRecord($pageParam, $this->uid, $this->link->channel_id,$this->link->id);
            }
        }
    }


    /**
     * 阅读
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function read()
    {
        $novel_id   = input('novel_id');
        $encrypt    = input('encrypt',0);
        $chapter_no = input('chapter_no');
        $push_id = input('push_id');
        if (!$this->link && $novel_id == '') {
            return errJson('参数异常');
        }
        if ($push_id != '') {
            /**推送代码（未做）*/
        }
        $replaceNid = 0;
        if ($this->link) {
            $novel_id = $this->link->novel_id;
            $chapter_no = $this->link->chapter_no;
            if ($this->link->status != 1 || (!$this->isWhite && (!$this->user->channel_id || $this->isBlack || $this->user->auditor || !ipUnblocked($this->user)))) {
                /**
                 * 替换链接书籍
                 * 不是白名单&&
                 * 无归属代理||黑名单||审核用户||IP屏蔽
                 */
                $replaceNid = \think\Db::table("quick_shield")->where("quick_id", $this->quickAppId)->value('link_replace_nid');
                if ($replaceNid) {
                    $novel_id = $replaceNid;
                    $chapter_no = '';
                }
            }
        }
        if ($chapter_no == '') {
            $where[] = ['uid', '=', $this->uid];
            $where[] = ['novel_id', '=', $novel_id];
            $chapter_no = Bookshelf::where($where)->value('chapter_no');
            if (!$chapter_no) {
                $chapter_no = 1;
            }
        }
        $today = date("Y-m-d");
        if ($today > "2024-04-08"){
            $redis = new BehaviorRedis();//新使用行为redis
        }else{
            $redis = new VoucherRedis();//消费凭证不让用了，会定时截断
        }
        $redis->addBookUv($this->quickAppId, $novel_id, date("Ymd"), $this->uid);//记录每日访问uv
        $data = UserLogic::read($this->user, $novel_id, $chapter_no);
        if (is_array($data)) {
            /**无替换书籍，说明不是屏蔽用户，允许弹出强关*/
            if ($this->link && !$replaceNid) {
                $data['linkInfo']['enter_pop'] = $this->link->enter_pop;
                $data['linkInfo']['force_switch'] = $this->link->force_switch;
                if ($this->link->force_switch == 1) {
                    $data['linkInfo']['force_chapter_no'] = $this->link->force_chapter_no;
                }
            }
            if($encrypt == 1)
            {
                $encrypt_data       = encryptTxt($data['content']);
                $data['content']    = $encrypt_data['encryptedData'];
                $data['iv']         = $encrypt_data['iv'];
            }
            return sucJson($data);
        }
        return $data;
    }

    /**
     * 书籍信息页
     * @return \think\response\Json
     * @Author: whh
     */
    public function info()
    {
        $novelId = input('novel_id');
        $params = $this->request->param();
        $result = $this->validate($params, 'app\reception\validate\NovelValidate.php.info');
        if (true !== $result) {
            return errJson($result);
        }
        $logic = new NovelLogic();
        return $logic->getNovelInfo($novelId);
    }

    /**
     * 章节列表接口
     * @return \think\response\Json
     */
    public function chapters()
    {
        $novelId = input('novel_id');
        $page = input('page', 1);
        $limit = input('limit', 10);
        $orderBy = input('order', 'asc');
        $params = $this->request->param();
        $result = $this->validate($params, 'app\reception\validate\NovelValidate.php.chapters');
        if (true !== $result) {
            return errJson($result);
        }
        $logic = new NovelLogic();
        return $logic->getNovelChapters($this->user, $novelId, $page, $limit, $orderBy);
    }


    public function list()
    {
        $novel_title = input('novel_title');
        $freq_id = input('freq_id');
        $class_id = input('class_id');
        $son_class_id = input('son_class_id');
        $update_status = input('update_status');
        $words_type = input('words_type');
        $order_type = input('order_type');
        $page = input('page', 1);
        $limit = input('limit', 10);

        $where[] = ['in_shelf', '=', 1];
        if ($novel_title != '') {
            $where[] = ['origin_title', 'like', "%{$novel_title}%"];
        }
        if ($freq_id != '') {
            $where[] = ['freq_id', '=', $freq_id];
        }
        if ($class_id != '') {
            $where[] = ['class_id', '=', $class_id];
        }
        if ($son_class_id != '') {
            $where[] = ['son_class_id', '=', $son_class_id];
        }
        if ($update_status != '') {
            $update_status = intval($update_status);
            if ($update_status === 0) {
                $where[] = ['update_status', 'in', [0, 2]];//对于读者来说，不需要体现弃更这个玩意
            } else {
                $where[] = ['update_status', '=', $update_status];
            }
        }
        switch ($words_type) {
            case 1:
                $where[] = ['number_words', '<=', 300000];
                break;
            case 2:
                $where[] = ['number_words', 'between', [300000, 500000]];
                break;
            case 3:
                $where[] = ['number_words', 'between', [500000, 1000000]];
                break;
            case 4:
                $where[] = ['number_words', 'between', [1000000, 2000000]];
                break;
            case 5:
                $where[] = ['number_words', '>', 2000000];
                break;
            default;
        }
        $orderBy = "id desc";
        switch ($order_type) {
            case 1:
                $orderBy = "popularity desc";
                break;
            case 2:
                $orderBy = "chapter_up_time desc";
                break;
            default;
        }
        /**
         * 市场用户 || 审核人员 || 黑名单 ：查看审核数据
         * 地区屏蔽 ：看C级书
         */
        if (!$this->isWhite) {
            if (!$this->user->channel_id || $this->isBlack || $this->user->auditor) {
                $novelIds = ExamineNovel::where('quick_id', $this->quickAppId)->column('novel_id');
                $where[] = ['id', 'in', $novelIds];
            } elseif (!ipUnblocked($this->user)) {
                $where[] = ['scale', '=', 'C'];
            }
        }
        $logic = new NovelLogic();
        return $logic->getNovels($this->user, $where, $page, $limit, $orderBy);
    }

}